<template>
  <CPageLayout :headerConfig="headerConfig">
    <template #headerDesc>
      <div class="g-flex-start-center">
        <span>创建人：{{ empty(detailInfo?.createBy) }}</span>
        <el-divider direction="vertical"></el-divider>
        <span>创建时间：{{ empty(detailInfo?.createTime) }}</span>
      </div>
    </template>
    <CPageTable @register="registerPage">
      <vxe-column title="排放单位" min-width="120">
        <template #default="scope">
          <span>{{ empty(scope.row.dischargeUnit) }}</span>
        </template>
      </vxe-column>
      <vxe-column title="年份" min-width="100">
        <template #default="scope">
          <span>{{ empty(scope.row.dischargeYear) }}</span>
        </template>
      </vxe-column>
      <vxe-column title="核查排放量(tCO₂)" min-width="120">
        <template #default="scope">
          <span>{{ empty(scope.row.carbonInspectEmission) }}</span>
        </template>
      </vxe-column>
      <vxe-column title="生产天数(天)" min-width="120">
        <template #default="scope">
          <span>{{ empty(scope.row.workDay) }}</span>
        </template>
      </vxe-column>
      <vxe-column title="配额计算(tCO₂)" min-width="120">
        <template #default="scope">
          <span>{{ empty(scope.row.annualQuotaCalculate) }}</span>
        </template>
      </vxe-column>
      <vxe-column title="配额缺口(tCO₂)" min-width="120">
        <template #default="scope">
          <span>{{ empty(scope.row.quotaGap) }}</span>
        </template>
      </vxe-column>
      <vxe-column title="应发配额(tCO₂)" min-width="120">
        <template #default="scope">
          <span>{{ empty(scope.row.annualQuotaGrant) }}</span>
        </template>
      </vxe-column>
      <vxe-column title="是否履约" min-width="120">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.performanceFlag">已履约</el-tag>
          <el-tag type="info" v-else>未履约</el-tag>
        </template>
      </vxe-column>
      <vxe-column title="操作" min-width="150">
        <template #default="scope">
          <CTableButtonGroup :buttons-config="getTableButtonsConfig(scope.row)" />
        </template>
      </vxe-column>
    </CPageTable>
    <AddOrEditFormDialog
      v-model:visible="formDialogVisible"
      :tempRow="tempRow"
      :readonly="formDialogReadonly"
      :dischargeUnitOption="dischargeUnitOption"
      @refresh="refresh"
    ></AddOrEditFormDialog>
    <ComplianceDialog
      v-model:visible="complianceVisible"
      :tempRow="tempRow"
      @refresh="refresh"
    ></ComplianceDialog>
  </CPageLayout>
</template>
<script lang="ts">
export default {
  name: 'MonitoringDetail'
};
</script>
<script lang="ts" setup>
import { ref, reactive, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { empty } from '@/utils';
import { getInspectInfo, getChildrenTree, deleteInspectTask } from '@/apis/taa/asset/inspect';
import { CPageLayout, CPageHeaderComplexProps } from '@/components/CPageLayout';
import { CTableButtonGroup } from '@/components/CTable';
import { CPageTable, useCPageTable, CPageTableProps } from '@/components/CPageTable';
import type { GetInspectListResult } from '@/apis/taa/asset/model/inspectModel';
import type { TableButtonItem } from '@/components/CTable';
import { useInspectList } from '../useInspectList';

import AddOrEditFormDialog from './components/AddOrEditFormDialog/index.vue';
import ComplianceDialog from './components/ComplianceDialog/index.vue';

import { useMessage } from '@/hooks/useMessage';

const route = useRoute();
const router = useRouter();
const { createMessage, createConfirm } = useMessage();
const { dischargeUnitOption } = useInspectList();
console.log(route, 'route', router, 'router');

const inspectNo = route.query.inspectNo as string;

// function handleRefresh() {
//   console.log('handleRefresh');
//   refresh();
// }

const detailInfo = reactive({
  dischargeUnit: '',
  dischargeYear: '',
  createBy: '',
  createTime: ''
});
async function getInspectInfoFn() {
  try {
    const data = await getInspectInfo(inspectNo);
    detailInfo.dischargeUnit = data.dischargeUnit;
    detailInfo.dischargeYear = data.dischargeYear;
    detailInfo.createBy = data.createBy;
    detailInfo.createTime = data.createTime;
  } catch (error) {
    console.log(error, 'error');
  }
}
getInspectInfoFn();

function loadData() {
  return getChildrenTree(inspectNo).then(res => {
    if (res && res.length) {
      const result = res;
      return {
        records: result,
        total: result?.length
      };
    } else {
      return {
        records: [],
        total: 0
      };
    }
  });
}

const headerConfig = computed<CPageHeaderComplexProps>(() => {
  return {
    title: `核查与履约数据明细 _ ${detailInfo.dischargeUnit} _ ${detailInfo.dischargeYear}`
  };
});

const options = reactive<CPageTableProps>({
  isDetailPage: true,
  isShowSearchBar: false,
  tableOptions: {
    loadData,
    pagination: false
  }
});
const [registerPage, { refresh }] = useCPageTable(options);

function getTableButtonsConfig(row: GetInspectListResult): TableButtonItem[] {
  const res = [];
  // 没有履约的
  if (!row.performanceFlag) {
    res.push({
      text: '编辑',
      btnPermission: 'TAA_VIEW_INSPECT_LIST_EDIT',
      onClick: () => handleEdit(row)
    });
    // 有年度核查量的可以进行履约
    if (typeof row.carbonInspectEmission === 'number' || row.carbonInspectEmission) {
      res.push({
        text: '履约',
        btnPermission: 'TAA_VIEW_INSPECT_LIST_HONOUR',
        onClick: () => handleOpenCompliance(row)
      });
    }
    res.push({
      text: '删除',
      btnPermission: 'TAA_VIEW_INSPECT_DELETE',
      onClick: () => handleDelete(row)
    });
    return res;
  } else {
    return [
      {
        text: '查看',
        btnPermission: 'TAA_VIEW_INSPECT_LIST',
        onClick: () => handleViewDetail(row)
      }
    ];
  }
}

const formDialogVisible = ref(false);
const tempRow = ref<GetInspectListResult>();
const formDialogReadonly = ref(false);
function handleEdit(row: GetInspectListResult) {
  formDialogReadonly.value = false;
  tempRow.value = row || undefined;
  formDialogVisible.value = true;
}

function handleDelete(row: GetInspectListResult) {
  createConfirm('提示', '确认删除该核查与履约？', {
    iconType: 'warning',
    confirmButtonText: '删除'
  }).then(() => {
    deleteInspectTask(row.inspectNo).then(() => {
      createMessage.success('删除成功！');
      refresh();
    });
  });
}

const complianceVisible = ref(false);
function handleOpenCompliance(row: GetInspectListResult) {
  complianceVisible.value = true;
  tempRow.value = row;
}

const handleViewDetail = (row: GetInspectListResult) => {
  formDialogReadonly.value = true;
  tempRow.value = row;
  formDialogVisible.value = true;
};
</script>
<style lang="scss" scoped>
:deep(.c-page-table) {
  .c-page-table__body .c-page-table__body-main.c-page-table__body-main--hide-search-bar {
    padding-top: 16px;
    padding-bottom: 60px;
  }
}
</style>
